<template>
    <div>
      <header class="header">
        <el-button @click="goBack" icon="left" type="text" class="back-button">
          <img src="@/assets/svgs/left.svg" alt="Back" />
        </el-button>
        <span class="title">课堂质量实时反馈</span>
        <div class="header-right">
          <el-button @click="confirmAddFeedback" type="text" class="feedback-button">发问卷</el-button>
        </div>
      </header>
      <div class="feedback-card-list">
        <div v-for="feedback in feedbacks" :key="feedback.id" class="feedback-card">
          <div class="feedback-title">第{{ feedback.id }}次反馈问卷</div>
          <div class="feedback-dates" style="margin-top: 10px;">开始时间：{{ formatDate(feedback.createTime) }}</div>
          <div class="feedback-submission" style="margin-top: 10px;">
            <div class="submission-label" style="font-size: 14px; color: gray; display: inline;">提交人数：</div>
            <div class="submission-number" style="display: inline;">{{ feedback.submittedCount }}/{{ feedback.totalCount }}</div>
          </div>
          <el-button @click="viewResults(feedback.id)" class="result-button">统计结果</el-button>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { ElMessageBox, ElMessage, ElLoading } from 'element-plus';
  import { getFeedbackList, createFeedback } from '@/api/feedback'; // 假设这是API路径

  const router = useRouter();
  const route = useRoute();
  const feedbacks = ref([]);
  const formData = ref({
    survey_name: '',
    class_id: ''
  });

  // 简化获取反馈列表的方法
  const fetchFeedbacks = async () => {
    const loading = ElLoading.service({
      lock: true,
      text: '加载中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    try {
      const response = await getFeedbackList();
      console.log('API响应数据:', response);

      if (!response || !response.data) {
        throw new Error('API返回数据格式错误');
      }

      const feedbackData = Array.isArray(response.data) ? response.data : [];
      feedbacks.value = feedbackData.map(item => ({
        id: item?.survey_id ?? '',
        createTime: item?.create_time ? new Date(item.create_time) : new Date(),
        submittedCount: Number(item?.submitted_count) || 0,
        totalCount: Number(item?.total_count) || 0
      }));

    } catch (error) {
      console.error('获取反馈列表错误:', error);
      feedbacks.value = [];
      ElMessage.error('获取反馈列表失败');
    } finally {
      loading.close();
    }
  };

  // 添加反馈
  const addFeedback = async () => {
    try {
      const classId = route.params.classId || route.query.classId;
      if (!classId) {
        throw new Error('未找到班级ID');
      }

      const feedbackData = {
        ...formData.value,
        classId
      };

      const response = await createFeedback(feedbackData);
      if (response && response.code === 200) {
        ElMessage.success('问卷添加成功');
        await fetchFeedbacks();
      } else {
        throw new Error(response?.message || '创建失败');
      }
    } catch (error) {
      console.error('创建问卷错误:', error);
      ElMessage.error(error.message || '创建问卷失败');
    }
  };

  // 组件挂载时获取数据
  onMounted(async () => {
    await fetchFeedbacks();
  });

  function formatDate(date) {
    const options = { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false };
    return new Intl.DateTimeFormat('zh-CN', options).format(date);
  }

  const confirmAddFeedback = () => {
    ElMessageBox.confirm('您确定要发问卷吗？', '提示', {
      confirmButtonText: '是',
      cancelButtonText: '否',
      type: 'warning',
      customClass: 'custom-message-box',
      confirmButtonClass: 'custom-confirm-button'
    }).then(() => {
      addFeedback();
    }).catch(() => {
      // 取消操作
    });
  };

  const goBack = () => {
    if (!router) {
      console.error('Router not initialized');
      window.location.href = '/teacher/dashboard';
      return;
    }
    
    try {
      router.push({
        path: '/teacher/dashboard'
      }).catch(err => {
        console.error('Navigation error:', err);
        window.location.href = '/teacher/dashboard';
      });
    } catch (error) {
      console.error('Navigation error:', error);
      window.location.href = '/teacher/dashboard';
    }
  };

  const viewResults = (id) => {
    if (!router) {
      console.error('Router not initialized');
      window.location.href = `/teacher/feedback/result/${id}`;
      return;
    }

    try {
      router.push({
        path: `/teacher/feedback/result/${id}`
      }).catch(err => {
        console.error('Navigation error:', err);
        window.location.href = `/teacher/feedback/result/${id}`;
      });
    } catch (error) {
      console.error('Navigation error:', error);
      window.location.href = `/teacher/feedback/result/${id}`;
    }
  };
  </script>
  
  <style>
  .template {
    background-color: #F9FAFB;
  }
  .header {
    color: white;
    padding: 10px;
    display: flex;
    align-items: center;
    background-color: #13227a;
    justify-content: space-between;
  }
  
  .back-button {
    color: white;
    border: none;
    width: 25px;
    height: 25px;
  }
  
  .title {
    margin-left: 10px;
  }
  
  .header-right {
    display: flex;
  }
  
  .feedback-button {
    background-color: #13227a;
    border: 1px solid white;
    color: white;
    width: 120px;
    height: 40px;
  }
  
  .feedback-card-list {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    margin-top: 20px;
    padding: 0 40px;
  }
  
  .feedback-card {
    background-color: white;
    border: 1px solid #ccc;
    border-radius: 5px;
    padding: 10px;
    height: 200px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }
  
  .feedback-title {
    font-weight: bold;
    color: black;
    font-size: 20px;
  }
  
  .feedback-dates {
    color: gray;
    font-size: 14px;
  }
  
  .feedback-submission {
    color: darkgray;
    display: flex;
    align-items: center;
    margin-top: 10px;
  }

  .result-button {
    background-color: #13227a;
    color: white;
    margin-top: auto;
    align-self: flex-end;
  }
  
  .custom-message-box {
    width: 400px !important;
    padding: 30px 20px !important;
  }

  .custom-message-box .el-message-box__message {
    font-size: 16px !important;
    padding: 20px 0 !important;
  }

  .custom-message-box .custom-confirm-button {
    background-color: #13227a !important;
    border-color: #13227a !important;
  }

  .custom-message-box .el-message-box__btns button {
    font-size: 14px !important;
    padding: 12px 20px !important;
  }
  </style>